package com.qiangesoft.design.creational.factorymethod;

/**
 * 工厂方法模式
 */
public class FactoryMethod {
    public static void main(String[] args) {
        // 使用工厂类来创建图形对象
        ShapeFactory circleFactory = new CircleFactory();
        Shape circle = circleFactory.createShape();
        circle.draw();

        ShapeFactory rectangleFactory = new RectangleFactory();
        Shape rectangle = rectangleFactory.createShape();
        rectangle.draw();
    }
}

/**
 * 1.定义一个图形接口
 */
interface Shape {
    void draw();
}

/**
 * 2.创建两个图形接口的实现类
 * Circle（圆形）、Rectangle（矩形）
 */
class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle");
    }
}

/**
 * 3.定义一个抽象工厂类
 * ShapeFactory定义一个抽象的工厂方法 createShape，子类将实现这个方法来创建具体的图形对象
 */
abstract class ShapeFactory {
    abstract Shape createShape();
}

/**
 * 4.创建两个具体的工厂类
 * CircleFactory 和 RectangleFactory分别实现了 ShapeFactory 并重写了 createShape 方法来返回相应的图形对象
 */
class CircleFactory extends ShapeFactory {
    @Override
    Shape createShape() {
        return new Circle();
    }
}

class RectangleFactory extends ShapeFactory {
    @Override
    Shape createShape() {
        return new Rectangle();
    }
}